﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.Serialization;
using System.ComponentModel;
using Windows.Storage;
using CC98.Data;
using CC98.Security;
using CC98.Storage;

namespace CC98.Data
{
    /// <summary>
    /// Account
    /// </summary>
    [DataContract(Namespace = Utility.Namespace)]
    public class Account: ISettingEntity
    {
        internal Account(string username)
        {
            this.Username = username;
        }

        internal Account(ApplicationDataCompositeValue value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            this.Read(value);
        }

        [DataMember]
        public string Username { get; private set; }

        /// <summary>
        /// Is remember this account or not
        /// </summary>
        [DataMember]
        public bool IsRemember { get; set; }

        /// <summary>
        /// Is saving password for this account
        /// Q:  How to save?
        /// </summary>
        [DataMember]
        public bool IsSavePassword { get; set; }

        /// <summary>
        /// The secured password
        /// </summary>
        [DataMember]
        public SecureString Password { get; set; }

        public virtual void Write(ApplicationDataCompositeValue value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            value["username"] = this.Username;
            value["isRemember"] = this.IsRemember;
            value["isSavePassword"] = this.IsSavePassword;
            if (this.IsSavePassword && this.Password != null)
                value["password"] = this.Password.ToString();
        }

        protected virtual void Read(ApplicationDataCompositeValue value)
        {
            this.Username = (string)value["username"];
            this.IsRemember = (bool)value["isRemember"];
            this.IsSavePassword = (bool)value["isSavePassword"];
            if (this.IsSavePassword)
                this.Password = new SecureString((string)value["password"]);
        }
    }
}
